﻿//-----------------------------------------------------------------------
//  This file is part of the Microsoft Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//-----------------------------------------------------------------------

namespace Microsoft.Samples.SqlServer
{
    #region Using directives

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Configuration;
    using System.Xml;
    using System.Diagnostics;

    #endregion

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1301:AvoidDuplicateAccelerators")]
    partial class MainForm : Form
    {
        public enum ImageListItems
        {
            ClosedFolder = 0,
            OpenFolder,
            Lock,
            Connection,
            ServerConnected,
            ServerDisconnected,
            Explorer,
            Trace
        };

        private enum AppNodeType
        {
            Undefined = 0,
            Group,
            Server,
            Connections,
            Sessions,
            Transactions,
            Locks,
            Traces
        };

        private const string KEY_COLUMN_CONNECTIONS = "CONNECTION_ID";
        private const string KEY_COLUMN_SESSIONS = "SESSION_ID";
        private const string KEY_COLUMN_SESSIONS_SPID = "SESSION_SPID";
        private const string KEY_COLUMN_TRANSACTIONS = "TRANSACTION_ID";
        //// private const string KEY_COLUMN_LOCKS = "LOCK_ID";
        private const string KEY_COLUMN_TRACES = "TraceID";

        private Utilities _utils = new Utilities();
        private int _selectedRow = -1;
        private string _selectedServer = string.Empty;
        private string _currentDiscoverType = ASCommands.DiscoverTypeNone;

        public MainForm()
        {
            InitializeComponent();
        }

        #region Form Events
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Microsoft.Samples.SqlServer.MainForm.DisplayMessage(System.String,System.String,System.Windows.Forms.MessageBoxIcon)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void MainForm_Load(object sender, EventArgs e)
        {
            // Load the list of registered servers
            try
            {
                XmlNodeList servers = Utilities.GetServers();
                foreach (XmlNode node in servers)
                {
                    this.LoadServerNode(node, null);
                }
            }
            catch (Exception ex)
            {
                this.DisplayMessage(
                    "Unable to load the list of registered servers.\n" + ex.Message,
                    "Application Error",
                    MessageBoxIcon.Error);
            }

            this.ClearTreeViewSelection();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (this._utils != null)
            {
                this._utils.Dispose();
            }
        }

        #endregion

        #region TreeView Events

        private void tvObjects_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            AppNodeType nodeType = GetNodeType(e.Node);

            // if moving to a node away from selected server, clear the grid
            if (nodeType == AppNodeType.Server)
            {
                this.SetSelectedServer(e.Node.Text);
            }
            else if (nodeType == AppNodeType.Group)
            {
                this.SetSelectedServer(string.Empty);
            }
            else if (this._selectedServer != e.Node.Parent.Text)
            {
                this.SetSelectedServer(e.Node.Parent.Text);
            }

            if (e.Button == MouseButtons.Left)
            {
                switch (nodeType)
                {
                    case AppNodeType.Server:
                        {
                            ASCommands obj
                                = this._utils.GetValidASCommandObject(this._selectedServer);
                            if (obj.IsConnected && e.Node.Nodes.Count == 0)
                            {
                                this.AddChildActionNodes(e.Node);
                                e.Node.Expand();
                            }
                            else
                            {
                                if (e.Node.IsExpanded && e.Node.IsSelected)
                                {
                                    e.Node.Collapse();
                                }
                                else if (obj.IsConnected)
                                {
                                    e.Node.Expand();
                                }
                            }
                            break;
                        }
                    case AppNodeType.Group:
                        {
                            if (e.Node.IsExpanded && e.Node.IsSelected)
                            {
                                e.Node.Collapse();
                            }
                            else
                            {
                                e.Node.Expand();
                            }

                            break;
                        }
                    default:
                        {
                            this.DoDiscoverNodeSelection(nodeType);
                            break;
                        }
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                if (nodeType == AppNodeType.Group)
                {
                    return;
                }

                // force node to be selected
                tvObjects.SelectedNode = e.Node;

                // show the context menu
                this.DisplayNodeContextMenu(nodeType);
            }
        }
        #endregion

        #region Grid Events

        private void grdResults_MouseUp(object sender, MouseEventArgs e)
        {
            Point pt = grdResults.PointToClient(Control.MousePosition);
            DataGridView.HitTestInfo hti = grdResults.HitTest(pt.X, pt.Y);
            if (hti.RowIndex >= 0 && e.Button == MouseButtons.Right)
            {
                grdResults.ClearSelection();
                grdResults.Rows[hti.RowIndex].Selected = true;

                // record which row is now the currently selected row
                this._selectedRow = hti.RowIndex;

                if (this._currentDiscoverType != ASCommands.DiscoverTypeLocks)
                {
                    cmGrid.Show(grdResults, pt);
                }
            }
        }

        private void grdResults_Sorted(object sender, EventArgs e)
        {
            this.SetSpecialRowForeColor(this._currentDiscoverType);
        }
        #endregion

        #region Context Menu Events: Servers

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Microsoft.Samples.SqlServer.MainForm.DisplayMessage(System.String,System.String,System.Windows.Forms.MessageBoxIcon)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmServersConnect_Click(object sender, EventArgs e)
        {
            ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);

            tvObjects.Refresh();
            grdResults.Refresh();
            if (!obj.IsConnected)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    obj.Connect();
                    tvObjects.SelectedNode.SelectedImageIndex
                        = (int)ImageListItems.ServerConnected;
                    this.AddChildActionNodes(tvObjects.SelectedNode);
                    tvObjects.SelectedNode.Expand();
                }
                catch (Exception ex)
                {
                    this.DisplayMessage(
                        "Error connecting to server.\n" + ex.Message,
                        "Application Error",
                        MessageBoxIcon.Error);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmServersDisconnect_Click(object sender, EventArgs e)
        {
            ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);

            tvObjects.Refresh();
            grdResults.Refresh();
            if (obj.IsConnected)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    obj.Disconnect();
                    tvObjects.SelectedNode.SelectedImageIndex
                        = (int)ImageListItems.ServerDisconnected;
                    tvObjects.SelectedNode.Collapse();
                    grdResults.DataSource = null;
                }
                catch (System.Exception ex)
                {
                    this.DisplayMessage(ex);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmServersNodeRefresh_Click(object sender, EventArgs e)
        {
            if (tvObjects.SelectedNode != null)
            {
                try
                {
                    this.DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
                }
                catch (Exception ex)
                {
                    this.DisplayMessage(ex);
                }
            }
        }

        #endregion

        #region Context Menu Events: Grid
        private void cmGrid_Opened(object sender, EventArgs e)
        {
            cmGridCancelSession.Visible = false;
            cmGridCancelConnection.Visible = false;
            cmGridCancelTransaction.Visible = false;
            cmGridShowSessions.Visible = false;
            cmGridShowTransactions.Visible = false;
            cmGridShowLocks.Visible = false;
            cmGridCancelTrace.Visible = false;
            toolStripSeparator1.Visible = false;

            switch (this._currentDiscoverType)
            {
                case ASCommands.DiscoverTypeConnections:
                    cmGridCancelConnection.Visible = true;
                    cmGridShowSessions.Visible = true;
                    toolStripSeparator1.Visible = true;
                    break;

                case ASCommands.DiscoverTypeSessions:
                    cmGridCancelSession.Visible = true;
                    cmGridShowTransactions.Visible = true;
                    toolStripSeparator1.Visible = true;
                    break;

                case ASCommands.DiscoverTypeTransactions:
                    // cmGridCancelTransaction.Visible = true;
                    cmGridShowLocks.Visible = true;
                    toolStripSeparator1.Visible = true;
                    break;
                case ASCommands.DiscoverTypeTraces:
                    cmGridCancelTrace.Visible = true;
                    break;

                default:
                    break;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridShowSessions_Click(object sender, EventArgs e)
        {
            try
            {
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                DataTable dt = obj.DiscoverSessions((int)
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_CONNECTIONS].Value);
                this.LoadGrid(dt, ASCommands.DiscoverTypeSessions);
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridShowTransactions_Click(object sender, EventArgs e)
        {
            try
            {
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                DataTable dt = obj.DiscoverTransactions(
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_SESSIONS].Value.ToString());
                this.LoadGrid(dt, ASCommands.DiscoverTypeTransactions);
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridShowLocks_Click(object sender, EventArgs e)
        {
            try
            {
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                DataTable dt = obj.DiscoverLocks(
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_TRANSACTIONS].Value.ToString());
                this.LoadGrid(dt, ASCommands.DiscoverTypeLocks);
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelConnection_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                obj.KillConnection((int)
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_CONNECTIONS].Value);
                LogItem item = new LogItem(
                    LogItem.LogType.Connection,
                    LogItem.LogAction.Cancel,
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_CONNECTIONS].Value,
                    this._selectedServer);
                Utilities.LogActivityItemBegin(item);

                // refresh the grid
                this.DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelSession_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                if (!obj.IsApplicationSession(
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_SESSIONS].Value.ToString()))
                {
                    obj.KillSession(
                        grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_SESSIONS].Value.ToString(),
                        (int)grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_SESSIONS_SPID].Value);
                    LogItem item = new LogItem(
                        LogItem.LogType.Session,
                        LogItem.LogAction.Cancel,
                        grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_SESSIONS_SPID].Value,
                        this._selectedServer);
                    item.AdditionalData.Add(
                        grdResults.Rows[this._selectedRow].Cells["SESSION_USER_NAME"].Value.ToString());
                    item.AdditionalData.Add(
                        grdResults.Rows[this._selectedRow].Cells["SESSION_ID"].Value.ToString());
                    Utilities.LogActivityItemBegin(item);

                    // refresh the grid
                    this.DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
                }
                else
                {
                    this.DisplayMessage("The selected session is in use by this application and can not be cancelled.", "Session In Use", MessageBoxIcon.Exclamation);
                }
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelTransaction_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                obj.KillTransaction(
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_TRANSACTIONS].Value.ToString());

                // refresh the grid
                this.DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelTrace_Click(object sender, EventArgs e) 
        {
            try {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);
                obj.KillTrace(
                    grdResults.Rows[this._selectedRow].Cells[KEY_COLUMN_TRACES].Value.ToString());

                //refresh the grid
                DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
            }
            catch (System.Exception ex) 
            {
                this.DisplayMessage(ex);
            }
            finally 
            { 
                this.Cursor = Cursors.Default; 
            }
        }
        #endregion

        #region Private support methods
        private void LoadServerNode(XmlNode node, TreeNode parent)
        {
            TreeNode tn = null;
            if (node.Name.Equals("GROUP", StringComparison.InvariantCultureIgnoreCase))
            {
                tn = new TreeNode(
                    node.Attributes["name"].Value,
                    (int)ImageListItems.ClosedFolder,
                    (int)ImageListItems.OpenFolder);
                tn.Tag = AppNodeType.Group;
            }
            else if (node.Name.Equals("SERVER", StringComparison.InvariantCultureIgnoreCase))
            {
                tn = new TreeNode(
                    node.Attributes["name"].Value,
                    (int)ImageListItems.ServerConnected,
                    (int)ImageListItems.ServerConnected);
                tn.Tag = AppNodeType.Server;
            }

            if (tn != null)
            {
                if (parent == null)
                {
                    tvObjects.Nodes.Add(tn);
                }
                else
                {
                    parent.Nodes.Add(tn);
                }

                if ((AppNodeType)tn.Tag == AppNodeType.Group
                    && node.ChildNodes.Count > 0)
                {
                    foreach (XmlNode child in node.ChildNodes)
                    {
                        this.LoadServerNode(child, tn);
                    }
                }
            }
        }

        private void SetSelectedServer(string selectedServer)
        {
            if (this._selectedServer != selectedServer
                || selectedServer.Length == 0)
            {
                this._selectedServer = selectedServer;
                grdResults.DataSource = null;
                lblDisplayedServer.Text = string.Empty;
            }
        }

        private void DisplayNodeContextMenu(AppNodeType nodeType)
        {
            foreach (ToolStripItem item in cmServers.Items)
            {
                item.Visible = item.Enabled = false;
            }

            if (nodeType == AppNodeType.Server)
            {
                ASCommands obj
                    = this._utils.GetValidASCommandObject(this._selectedServer);
                if (obj.IsConnected)
                {
                    cmServersConnect.Visible = true;
                    cmServersDisconnect.Visible
                        = cmServersDisconnect.Enabled = true;
                }
                else
                {
                    cmServersConnect.Visible = cmServersConnect.Enabled = true;
                    cmServersDisconnect.Visible = true;
                }
            }
            else
            {
                cmServersNodeRefresh.Visible
                    = cmServersNodeRefresh.Enabled = true;
            }

            // display context menu
            Point pt = tvObjects.PointToClient(Control.MousePosition);
            cmServers.Show(tvObjects, pt);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.TreeNode.#ctor(System.String,System.Int32,System.Int32)")]
        private void AddChildActionNodes(TreeNode node)
        {
            if (node.Nodes.Count > 0)
            {
                return;
            }

            tvObjects.SuspendLayout();
            TreeNode tn = new TreeNode(
                ASCommands.DiscoverNameConnections,
                (int)ImageListItems.Connection,
                (int)ImageListItems.Connection);
            tn.Tag = AppNodeType.Connections;
            node.Nodes.Add(tn);

            tn = new TreeNode(
                ASCommands.DiscoverNameSessions,
                (int)ImageListItems.Explorer,
                (int)ImageListItems.Explorer);
            tn.Tag = AppNodeType.Sessions;
            node.Nodes.Add(tn);

            tn = new TreeNode(
                ASCommands.DiscoverNameTransactions,
                (int)ImageListItems.Explorer,
                (int)ImageListItems.Explorer);
            tn.Tag = AppNodeType.Transactions;
            node.Nodes.Add(tn);

            tn = new TreeNode(
                ASCommands.DiscoverNameLocks,
                (int)ImageListItems.Lock,
                (int)ImageListItems.Lock);
            tn.Tag = AppNodeType.Locks;
            node.Nodes.Add(tn);

            tn = new TreeNode(
                ASCommands.DiscoverNameTraces, 
                (int)ImageListItems.Trace, 
                (int)ImageListItems.Trace);
            tn.Tag = AppNodeType.Traces;
            node.Nodes.Add(tn);

            tvObjects.ResumeLayout();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void DoDiscoverNodeSelection(AppNodeType nodeType)
        {
            DataTable dt = null;
            string discoverType = ASCommands.DiscoverTypeNone;

            this.Cursor = Cursors.WaitCursor;

            try
            {
                ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);

                // find out which node was selected
                switch (nodeType)
                {
                    case AppNodeType.Connections:
                        dt = obj.DiscoverConnections();
                        discoverType = ASCommands.DiscoverTypeConnections;
                        break;

                    case AppNodeType.Sessions:
                        dt = obj.DiscoverSessions();
                        discoverType = ASCommands.DiscoverTypeSessions;
                        break;

                    case AppNodeType.Transactions:
                        dt = obj.DiscoverTransactions();
                        discoverType = ASCommands.DiscoverTypeTransactions;
                        break;

                    case AppNodeType.Locks:
                        dt = obj.DiscoverLocks();
                        discoverType = ASCommands.DiscoverTypeLocks;
                        break;

                    case AppNodeType.Traces:
                        dt = obj.DiscoverTraces();
                        discoverType = ASCommands.DiscoverTypeTraces;
                        break;

                }

                this.LoadGrid(dt, discoverType);
            }
            catch (Exception ex)
            {
                this.DisplayMessage(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private bool LoadGrid(DataTable dataTable, string discoverType)
        {
            try
            {
                grdResults.SuspendLayout();

                // clear the grid
                grdResults.DataSource = null;
                this._selectedRow = -1;

                // Load new data
                lblDisplayedServer.Visible = true;
                lblDisplayedServer.Text = this._selectedServer;
                this._currentDiscoverType = discoverType;
                grdResults.DataSource = dataTable;
                grdResults.AutoResizeColumns(
                    DataGridViewAutoSizeColumnsMode.ColumnHeader);
                grdResults.AllowUserToResizeColumns = true;

                // Set column display order
                this.SetColumnDisplayOrder();

                // set ForeColor for rows that are in the monitored items collection
                // or are sessions tied to this application
                this.SetSpecialRowForeColor(discoverType);

                return true;
            }
            catch (Exception ex)
            {
                this.DisplayMessage(ex);
                return false;
            }
            finally
            {
                grdResults.ResumeLayout();
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void SetSpecialRowForeColor(string discoverType)
        {
            ASCommands obj = this._utils.GetValidASCommandObject(this._selectedServer);

            for (int row = 0; row < grdResults.Rows.Count; row++)
            {
                DataGridViewRow dgvr = grdResults.Rows[row];

                // check for connections/sessions created by this application
                switch (discoverType)
                {
                    case ASCommands.DiscoverTypeSessions:
                        if (obj.IsApplicationSession(
                            dgvr.Cells[KEY_COLUMN_SESSIONS].Value.ToString()))
                        {
                            dgvr.DefaultCellStyle.ForeColor = Color.Gray;
                        }

                        break;

                    case ASCommands.DiscoverTypeConnections:
                        if (obj.IsApplicationConnection(
                            dgvr.Cells[KEY_COLUMN_CONNECTIONS].Value.ToString()))
                        {
                            dgvr.DefaultCellStyle.ForeColor = Color.Gray;
                        }

                        break;
                }
            }
        }

        private void SetColumnDisplayOrder()
        {
            switch (this._currentDiscoverType)
            {
                case ASCommands.DiscoverTypeSessions:
                    grdResults.Columns["SESSION_SPID"].DisplayIndex = 0;
                    grdResults.Columns["SESSION_CONNECTION_ID"].DisplayIndex = 1;
                    grdResults.Columns["SESSION_USER_NAME"].DisplayIndex = 2;
                    grdResults.Columns["SESSION_CURRENT_DATABASE"].DisplayIndex = 3;
                    //// grdResults.Columns["SESSION_LAST_REQUEST"].DisplayIndex = 4;
                    grdResults.Columns["SESSION_LAST_COMMAND_START_TIME"].DisplayIndex = 4;
                    grdResults.Columns["SESSION_LAST_COMMAND_ELAPSED_TIME_MS"].DisplayIndex = 5;
                    grdResults.Columns["SESSION_LAST_COMMAND_END_TIME"].DisplayIndex = 6;
                    grdResults.Columns["SESSION_CPU_TIME_MS"].DisplayIndex = 7;
                    grdResults.Columns["SESSION_START_TIME"].DisplayIndex = 8;
                    grdResults.Columns["SESSION_ELAPSED_TIME_MS"].DisplayIndex = 9;
                    grdResults.Columns["SESSION_IDLE_TIME_MS"].DisplayIndex = 10;
                    grdResults.Columns["SESSION_USED_MEMORY"].DisplayIndex = 11;
                    grdResults.Columns["SESSION_PROPERTIES"].DisplayIndex = 12;
                    grdResults.Columns["SESSION_ID"].DisplayIndex = 13;
                    break;

                case ASCommands.DiscoverTypeConnections:
                    break;

                default:
                    break;
            }
        }

        private static AppNodeType GetNodeType(TreeNode node)
        {
            if (node.Tag != null && node.Tag is AppNodeType)
            {
                return (AppNodeType)node.Tag;
            }
            else
            {
                return AppNodeType.Undefined;
            }
        }

        private void ClearTreeViewSelection()
        {
            lblDisplayedServer.Text = string.Empty;
            grdResults.DataSource = null;
            tvObjects.SelectedNode = null;
        }

        private void DisplayMessage(string message, string caption, MessageBoxIcon icon)
        {
            MessageBox.Show(
                this,
                message,
                caption,
                MessageBoxButtons.OK,
                icon,
                MessageBoxDefaultButton.Button1,
                0);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.MessageBox.Show(System.Windows.Forms.IWin32Window,System.String,System.String,System.Windows.Forms.MessageBoxButtons,System.Windows.Forms.MessageBoxIcon,System.Windows.Forms.MessageBoxDefaultButton,System.Windows.Forms.MessageBoxOptions)")]
        private void DisplayMessage(System.Exception ex)
        {
            string message = ex.Message;
            if (ex.InnerException != null)
            {
                message += "\n" + ex.InnerException.Message;
            }

            string finalMessage
                = "An error has occurred in the application: \n\n" + message;
            MessageBox.Show(
                this,
                finalMessage,
                "Application Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error,
                MessageBoxDefaultButton.Button1,
                0);
        }
        #endregion


        #region ToolStrip Menu Events

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (grdResults.DataSource == null)
            {
                SaveAsToolStripMenuItem.Enabled = false;
            }
            else
            {
                SaveAsToolStripMenuItem.Enabled = true;
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm frm = new AboutForm();
            frm.ShowDialog(this);
            frm.Dispose();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // close the form to let the appliation exit
            this.Close();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog.FileName = "*.txt";
                saveFileDialog.Filter
                    = "Tab Delimited(.txt)|.txt|Comma Delimited(.csv)|.csv";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.InitialDirectory = Application.ExecutablePath;

                if (saveFileDialog.ShowDialog(this) == DialogResult.Cancel)
                {
                    return;
                }

                string filePath = saveFileDialog.FileName;

                switch (saveFileDialog.FilterIndex)
                {
                    case 1:
                        Utilities.SaveDataTableToFile(
                            (DataTable)grdResults.DataSource, "\t", filePath);
                        break;

                    default:
                        Utilities.SaveDataTableToFile(
                            (DataTable)grdResults.DataSource, ",", filePath);
                        break;
                }
            }
            catch (System.Exception ex)
            {
                this.DisplayMessage(ex);
            }
        }
        #endregion
    }
}